package com.codemart.service.impl;

import com.codemart.constant.JwtHeaderConstant;
import com.codemart.constant.MessageConstant;
import com.codemart.constant.ProjectDetailConstant;
import com.codemart.dto.*;
import com.codemart.exception.BaseException;
import com.codemart.exception.LoginFailedException;
import com.codemart.exceptions.ServiceException;
import com.codemart.mapper.ProjectMapper;
import com.codemart.mapper.UserInfoMapper;
import com.codemart.service.UserInfoService;
import com.codemart.util.JwtUtil;
import com.codemart.vo.UserVO;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.security.auth.login.LoginContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    ProjectMapper projectMapper;

    @Override
    public UserInfoDTO userInfo(HttpServletRequest request) {
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        if(token != null){
            Integer userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = Integer.valueOf(claims.getSubject());
            } catch (Exception e) {
                throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);
            }
            return userInfoMapper.userInfo(userid);
        }else{
            return null;
        }
    }

    @Override
    public List<MyProjectsDTO> getMyProject(HttpServletRequest request) {

        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        List<MyProjectsDTO> myProject = null;

        if(token != null){
            Integer userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = Integer.valueOf(claims.getSubject());
            } catch (Exception e) {
                throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);
            }
            if(userid != null){
                myProject = userInfoMapper.getMyProject(userid);
            }
            myProject.forEach(pro->{
                if(pro.getStatus_name().equals(ProjectDetailConstant.IS_PROGRESS) || pro.getStatus_name().equals(ProjectDetailConstant.PREPARATION_STAGE)){
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String nowDate = df.format(new Date());
                    try {
                        Date cT = df.parse(pro.getCreate_time());
//                        long sup = (df.parse(nowDate).getTime() - cT.getTime()) / 1000;
                        long sup = (df.parse(nowDate).getTime() - cT.getTime()) / 1000 / 60 / 60 / 24;
                        if(sup >= Long.parseLong(pro.getTerm_day())){
                            projectMapper.updateProjectStatus(pro.getDe_id(),6);
                            projectMapper.updateProjectPlan(pro.getDe_id(),6);
                            pro.setStatus_name(ProjectDetailConstant.IS_CLOSED);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                        throw new BaseException(MessageConstant.UNKNOWN_ERROR);
                    }
                }
            });
        }
        return myProject;
    }

    @Override
    @Transactional
    public void updateUserDetail(HttpServletRequest request, UserDetailDTO ud) {
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        if (token != null) {
            Integer userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = Integer.valueOf(claims.getSubject());
            } catch (Exception e) {
                throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);
            }

            if(ud.getBirthday().equals(ProjectDetailConstant.IS_NOT_SET)){
                ud.setBirthday(null);
            }
            if(ud.getPhone().equals(ProjectDetailConstant.IS_NOT_SET)){
                ud.setPhone(null);
            }
            if(ud.getAddress().equals(ProjectDetailConstant.IS_NOT_SET)){
                ud.setAddress(null);
            }
            System.out.println(ud);

            try{
                userInfoMapper.updateUserLogin(userid,ud.getNickname());
                userInfoMapper.updateUserInfo(userid,ud.getAddress(),ud.getBirthday(),ud.getPhone());
                if(ud.getSku_id() != null){
                    UserSkuDTO userSku = userInfoMapper.getUserSku(userid);
                    if(userSku == null){
                        userInfoMapper.insertUserSku(userid, ud.getSku_id());
                    }else{
                        System.out.println(ud.getSku_id());
                        userInfoMapper.updateUserSku(userid, ud.getSku_id());
                    }
                }else{
                    userInfoMapper.deleteUserSku(userid);
                }
            }catch (Exception e){
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
    }

    @Override
    public List<MyBiddingInfoDTO> listMyBidding(HttpServletRequest request) {
        String token = request.getHeader(JwtHeaderConstant.TOKEN_NAME_LOWER);
        if (token != null) {
            Integer userid;
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = Integer.valueOf(claims.getSubject());
            } catch (Exception e) {
                throw new LoginFailedException(MessageConstant.LOGIN_INFORMATION_IS_INCORRECT);
            }
            try{
                return userInfoMapper.listMyBidding(userid);
            }catch (Exception e){
                throw new BaseException(MessageConstant.UNKNOWN_ERROR);
            }
        }
        return null;
    }
}
